package com.tianji.learning.handler;

import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.DateUtils;
import com.tianji.learning.constants.RedisConstants;
import com.tianji.learning.domain.po.PointsBoard;
import com.tianji.learning.service.IPointsBoardSeasonService;
import com.tianji.learning.service.IPointsBoardService;
import com.tianji.learning.utils.TableInfoContext;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

import static com.tianji.learning.constants.LearningConstants.POINTS_BOARD_TABLE_PREFIX;

/**
 * @description
 * @author: ZXX-挚爱
 * @time: 2023/8/2 0:38
 */
@RequiredArgsConstructor
@Component
@Slf4j
public class PointBoardPersistentHandler {
    private final IPointsBoardSeasonService seasonService;

    private final IPointsBoardService pointsBoardService;

    private final StringRedisTemplate redisTemplate;


    @XxlJob("createTableJob")
    public void createPointsBoardTableOfLastSeason() {
        // 1.获取上月时间
        LocalDateTime time = LocalDateTime.now().minusMonths(1);
        // 2.查询赛季id
        Integer season = seasonService.querySeasonByTime(time);
        if (season == null) {
            // 赛季不存在
            return;
        }
        // 3.创建表
        pointsBoardService.createBoardTableBySeason(season);
    }

    @XxlJob("savePointBoard2DB")
    public void savePointsBoard2DB(){
        //1.获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //2.获取上个月时间
        LocalDateTime time = now.minusMonths(1);
        //2.1.查询赛季信息
        Integer seasonId=seasonService.querySeasonByTime(time);
        //2.2.表名存入ThreadLocal
        TableInfoContext.setInfo(POINTS_BOARD_TABLE_PREFIX+seasonId);
        //3.查询榜单数据
        //3.1.拼接key
        String key= RedisConstants.POINTS_BOARD_KEY_PREFIX+time.format(DateUtils.POINTS_BOARD_SUFFIX_PREFIX);
        //3.2查询数据
        int index= XxlJobHelper.getShardIndex();
        int total= XxlJobHelper.getShardTotal();
        int pageNo= index+1;
        int pageSize=10;

        while (true) {
            List<PointsBoard> boardList=pointsBoardService.queryCurrentBoardList(key,pageNo,pageSize);
            if (CollUtils.isEmpty(boardList)) {
                break;
            }
            //4.持久化到数据库
            boardList.forEach(b->{
                b.setId(b.getRank().longValue());
                b.setRank(null);
            });
            //4.2.
            pointsBoardService.saveBatch(boardList);
            //5.翻页
            pageNo+=total;
        }
        //定时任务结束,移除动态表面
        TableInfoContext.remove();
    }

    @XxlJob("clearPointsBoardFromRedis")
    public void clearPointsBoardFromRedis(){
        log.info("任务结束,清理redis缓存任务");
        //1.获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //2.获取上个月时间
        LocalDateTime time = now.minusMonths(1);
        //3.根据上个月的时间查询赛季ID
        String key= RedisConstants.POINTS_BOARD_KEY_PREFIX+time.format(DateUtils.POINTS_BOARD_SUFFIX_PREFIX);
        //4.删除缓存任务
        redisTemplate.unlink(key);
    }
}
